package com.imooc.miaosha.exception;

import com.imooc.miaosha.result.CodeMsg;
import com.imooc.miaosha.result.Result;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import org.springframework.validation.BindException;

import java.util.List;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public Result<String> exceptionHandler(HttpServletRequest request,Exception e){
        e.printStackTrace();

        if(e instanceof GlobalException){
            GlobalException ge = (GlobalException) e;

            CodeMsg codeMsg = ge.getCodeMsg();
            return Result.error(codeMsg);
        } else if(e instanceof BindException){
            //获取错误列表，拿取其中的第一个
            BindException be = (BindException) e;
            List<ObjectError> allErrors = be.getAllErrors();
            ObjectError error = allErrors.get(0);

            String message = error.getDefaultMessage();
            return Result.error(CodeMsg.BIND_ERROR.fillArgs(message));
        }else {
            return Result.error(CodeMsg.SERVER_ERROR);
        }

    }
}
